<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<button class="back-arrow" @click="goBack"></button>
			<p>编辑送货地址</p>
		</header>
		<!-- 表单部分 -->
		<ul class="form-box">
			<li>
				<div class="title">
					联系人：
				</div>
				<div class="content">
					<input type="text" v-model="deliveryAddress.contactName" placeholder="联系人姓名">
				</div>
			</li>
			<li>
				<div class="title">
					性别：
				</div>
				<div class="content" style="font-size: 3vw;">
					<input type="radio" v-model="deliveryAddress.contactSex" value="1" style="width:6vw;height:3.2vw;"
						checked>男
					<input type="radio" v-model="deliveryAddress.contactSex" value="0" style="width:6vw;height:3.2vw;">女
				</div>
			</li>
			<li>
				<div class="title">
					电话：
				</div>
				<div class="content">
					<input type="tel" v-model="deliveryAddress.contactTel" placeholder="电话">
				</div>
			</li>
			<li>
				<div class="title">
					收货地址：
				</div>
				<div class="content">
					<input type="text" v-model="deliveryAddress.address" placeholder="收货地址">
				</div>
			</li>
		</ul>
		<div class="button-add">
			<button @click="editUserAddress">更新</button>
		</div>
		 <!-- Alert Modal -->
		 <alert-modal v-if="alertVisible" :visible.sync="alertVisible" :message="alertMessage"></alert-modal>
		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>
<script>
	import Footer from '../components/Footer.vue';
	import JSEncrypt from 'jsencrypt';
	import request from '../request.js';
	import AlertModal from '../views/AlertModal.vue';
	export default {
		name: 'EditUserAddress',
		data() {
			return {
				alertVisible: false,
				alertMessage: '',
				businessId: this.$route.query.businessId,
				daId: this.$route.query.daId,
				user: {},
				deliveryAddress: {}
			}
		},
		created() {
			this.user = this.$getSessionStorage('user');

			// 生成RSA密钥对
			const rsa = new JSEncrypt();
  			const keypair = rsa.getKey();

  			// 获取公钥和私钥
  			const publicKeyPem = keypair.getPublicKey();
  			const privateKeyPem = keypair.getPrivateKey();
  			const publicKey = publicKeyPem.replace(/-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----|\n/g, '');
			const privateKey = privateKeyPem.replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\n/g, '');
  			// 发起请求获取加密的送货地址信息
  			request.get('delivery-addresses/', {
    			params: {
					daId: this.daId,
      				publicKey: publicKey
    			}
  			}).then(response => {
    			this.deliveryAddress = response.data;
    			// 对联系电话和地址信息进行解密
      			const encryptor = new JSEncrypt();
      			encryptor.setPrivateKey(privateKey); // 设置私钥
      			this.deliveryAddress.contactTel = encryptor.decrypt(this.deliveryAddress.contactTel) ; // 解密手机号
      			this.deliveryAddress.address = encryptor.decrypt(this.deliveryAddress.address) ; // 解密地址
  			}).catch(error => {
    			console.error(error);
  			});
		},
		components: {
			Footer,AlertModal
		},
		methods: {
			goBack() {
				console.log('Trying to go back...');
                this.$router.go(-1); // 相当于浏览器的后退操作
                },
			async editUserAddress() {
				const regex = /^1.{10}$/;
				if (this.deliveryAddress.contactName == '') {
					this.alertMessage ='联系人姓名不能为空！';
					this.alertVisible = true;
					return;
				}
				if (!regex.test(this.deliveryAddress.contactTel)) {
				    this.alertMessage ='联系人电话不正确!';
					this.alertVisible = true;
				    return;
				}
				if (this.deliveryAddress.contactTel == '') {
					this.alertMessage ='联系人电话不能为空！';
					this.alertVisible = true;
					return;
				}
				if (this.deliveryAddress.address == '') {
					this.alertMessage ='联系人地址不能为空！';
					this.alertVisible = true;
					return;
				}

				await request.get(`users/key/${this.user.userId}`).then(response => {//获取公钥
		  			this.PublicKey = response.data;
				}).catch(error => {
		  			console.error(error);
				});
				const encryptor = new JSEncrypt()//rsa加密
      			encryptor.setPublicKey(this.PublicKey)  // 放入公钥
      			let contactTelAfter = encryptor.encrypt(this.deliveryAddress.contactTel)  // 加密手机号
				let addressAfter = encryptor.encrypt(this.deliveryAddress.address)  // 加密地址

				await request.put(`delivery-addresses/${this.daId}`,
					this.$qs.stringify({
						contactName:this.deliveryAddress.contactName,
						contactSex:this.deliveryAddress.contactSex,
						contactTel:contactTelAfter,
						address:addressAfter,
						userId:this.deliveryAddress.userId
					})).then(response => {
					if (response.data > 0) {
						this.$router.push({
							path: '/userAddress',
							query: {
								businessId: this.businessId
							}
						});
					} else {
						this.alertMessage ='更新地址失败！';
						this.alertVisible = true;
					}
				}).catch(error => {
					console.error(error);
				});
			}
		}
	}
</script>
<style scoped>
	/*************** 总容器 ***************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/*************** header ***************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		display: flex;
		justify-content: space-around;
		align-items: center;
		color: #fff;
		font-size: 4.8vw;
		position: fixed;
		left: 0;
		top: 0;
		/*保证在最上层*/
		z-index: 1000;
	}
   /****************** 返回键 ******************/
 
   .back-arrow {
  position: fixed; /* 固定定位 */
  left: 2.5vw; /* 距离屏幕左端像素 */
  top: 2.5vw; /* 距离屏幕顶部像素 */
  width: 8vw; /* 使用视口宽度的百分比 */
  height: 8vw; /* 使用视口宽度的百分比，保持宽高比 */
  background-color: rgba(0, 151, 255, 0.5); /* 半透明的背景颜色 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border: none; /* 隐藏边框 */
  transition: background-color 0.3s ease; /* 背景颜色变化动画 */
}

.back-arrow::before {
  content: '\f053'; /* 使用 FontAwesome 的左箭头图标 */
  font-family: 'FontAwesome'; /* FontAwesome 字体 */
  font-size: 5vh; /* 使用视口高度的百分比，确保在不同设备上也合适 */
  color: #fff; /* 字体颜色 */
  transition: color 0.3s ease; /* 字体颜色变化动画 */
}

.back-arrow:hover::before {
  color: #0a2ddc; /* 鼠标悬停时的颜色变化 */
}

.back-arrow:hover {
  background-color: rgba(0, 151, 255, 0.3); /* 鼠标悬停时的背景颜色变化为更透明 */
}
	/*************** （表单信息） ***************/
	.wrapper .form-box {
		width: 100%;
		margin-top: 12vw;
	}

	.wrapper .form-box li {
		box-sizing: border-box;
		padding: 4vw 3vw 0vw 3vw;
		display: flex;
	}

	.wrapper .form-box li .title {
		flex: 0 0 18vw;
		font-size: 3vw;
		font-weight: 700;
		color: #666;
		
	}

	.wrapper .form-box li .content {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.wrapper .form-box li .content input {
		border: none;
		outline: none;
		width: 100%;
		height: 4vw;
		font-size: 3vw;
	}

	.wrapper .button-add {
		box-sizing: border-box;
		padding: 4vw 3vw 0vw 3vw;
	}

	.wrapper .button-add button {
		width: 100%;
		height: 10vw;
		font-size: 3.8vw;
		font-weight: 700;
		border: none;
		outline: none;
		border-radius: 4px;
		color: #fff;
		background-color: #38CA73;
	}
</style>